/**
 * @Title: UserController.java
 * @Package www.codepeople.cn.controller
 * @Description: 
 * Copyright: Copyright (c) 2019 www.codepeople.cn Inc. All rights reserved. 
 * Website: www.codepeople.cn
 * 注意：本内容仅限于海南科澜技术信息有限公司内部传阅，禁止外泄以及用于其他的商业目 
 * @Author 刘仁
 * @DateTime 2019年4月1日 下午5:29:03
 * @version V1.0
 */

package www.codepeople.cn.controller;

import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import www.codepeople.cn.entity.ResponseBean;
import www.codepeople.cn.entity.User;
import www.codepeople.cn.service.UserService;
import www.codepeople.cn.util.JWTUtil;

/**
 * @ClassName: UserController
 * @Description: 
 * @Author 刘仁
 * @DateTime 2019年4月1日 下午5:29:03 
 */
@RestController
public class UserController {

	@Autowired
	private UserService userService;
	
	@PostMapping("/login")
	@ApiOperation(value="登录功能", notes="用户密码登录")
	@ApiImplicitParams({
         @ApiImplicitParam(name = "username", value = "用户名", required = true, dataType = "String"),
         @ApiImplicitParam(name = "password", value = "密码", required = true, dataType = "String")
	 })
	public ResponseBean login(@RequestParam("username") String username,
							  @RequestParam("password") String password,
							  HttpServletResponse response) throws UnsupportedEncodingException {
		User user = userService.getUser(username);
		if (user.getPassword().equals(password)) {
			String token = JWTUtil.sign(username, password);
			response.setHeader("token", token);
			return new ResponseBean(200, "登录成功", token);
		} else {
			throw new UnauthorizedException();
		}
	}
	
	@GetMapping("/listUser")
	@ApiOperation(value="获取用户列表", notes="获取用户列表")
	public ResponseBean listUser() throws UnsupportedEncodingException {
		List<User> listUser = userService.listUser();
		return new ResponseBean(200, "用户列表", listUser);
	}
	
	@RequestMapping("/401")
	@ResponseStatus(HttpStatus.UNAUTHORIZED)
	public ResponseBean unauthorized() {
		return new ResponseBean(401, "未授权", null);
	}
}
